import re

from pypinyin import lazy_pinyin


def chinese_character(c):
    """判断一个字符是否为汉字"""
    return '\u4e00' <= c <= '\u9fa5'


def ling(c):
    """判断一个字符是否为汉字"〇"""
    return c == '\u3007'


def get_chinese_part(text):
    """得到文本中的中文部分"""
    pattern = re.compile(r'([\u3007\u4e00-\u9fa5]+)')
    segments = pattern.findall(text)

    return "".join(segments)


def text2token(text, tokenizer):
    """将文本中的汉字转化为拼音，将非汉字转化为`[OTHER]`"""
    chinese_part = get_chinese_part(text)
    # print('chinese_part', chinese_part)
    cn_char_pinyin = lazy_pinyin(chinese_part)
    # print('cn_char_pinyin', cn_char_pinyin)
    text_tokens = tokenizer.tokenize(text)
    # print('text_tokens:', text_tokens)
    text_tokens_no_unk = []
    base_index = 0
    for token in text_tokens:
        if token != "[UNK]":
            text_tokens_no_unk.append(token)
            # base_index = text.index(token)
            # text = text[base_index+1:]
            text = text[len(token.strip("##")):]
        else:
            text_tokens_no_unk.append(text[0])
            text = text[1:]
    pinyin_tokens = []
    i = 0
    # print('chinese_part', 'chinese_part')
    # print('text_tokens_no_unk', text_tokens_no_unk)
    # aaa = []
    for token in text_tokens_no_unk:
        # if chinese_character(token) or ling(token):
        #     aaa.append(token)
        #     print(aaa)
        if chinese_character(token) or ling(token):
            pinyin_tokens.append(cn_char_pinyin[i])
            i += 1
            # pinyin_tokens.append(cn_char_pinyin[chinese_part.index(token)])
        else:
            pinyin_tokens.append("[OTHER]")
    return text_tokens_no_unk, pinyin_tokens


def token2ids(pinyin_tokens, pinyin_vocab):
    """根据tokenizer的分词规则，将中文部分转化为pinyin_vocab中的id，非中文部分转化为0"""
    pinyin_ids = list(map(lambda x: pinyin_vocab.get(x, 0), pinyin_tokens))
    return pinyin_ids


def replace_para(para, text):
    idx = 0
    for i, run in enumerate(para.runs):
        run_len = len(run.text)
        
        if i == len(para.runs) - 1:
            run.text = text[idx:]
        else:
            run.text = text[idx:idx+run_len]
        idx = idx + run_len


def insert_whitespace(source, target):
    result = ''
    target_index = 0
    for char in source:
        if char.isspace():
            result += char
        else:
            result += target[target_index]
            target_index += 1
    return result
